package com.lucher.tangstore.common;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;



import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpTools {



	/**
     * 向指定 URL 发送GET方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
	public static void get(String url){
	     CloseableHttpClient httpClient = null;
	     HttpGet httpGet = null;
	     try {
	         httpClient = HttpClients.createDefault();
	         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
	         httpGet = new HttpGet(url);
	         httpGet.setConfig(requestConfig);
	         CloseableHttpResponse response = httpClient.execute(httpGet);
	         HttpEntity httpEntity = response.getEntity();
	         System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
	     } catch (ClientProtocolException e) {
	         e.printStackTrace();
	     } catch (IOException e) {
	         e.printStackTrace();
	     }finally{
	         try {
	             if(httpGet!=null){
	                 httpGet.releaseConnection();
	             }
	             if(httpClient!=null){
	                 httpClient.close();
	             }
	         } catch (IOException e) {
	             e.printStackTrace();
	         }
	     }
	 }
	
	 /**
     * 向指定 URL 发送GET方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param 参数放到Map中
     * @return 所代表远程资源的响应结果
     */
	public static void get(String url, Map<String, String> params){
	     CloseableHttpClient httpClient = null;
	     HttpGet httpGet = null;
	     try {
	         httpClient = HttpClients.createDefault();
	         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
	         String ps = "";
	         for (String pKey : params.keySet()) {
	             if(!"".equals(ps)){
	                 ps = ps + "&";
	             }
	             ps = pKey+"="+params.get(pKey);
	         }
	         if(!"".equals(ps)){
	             url = url + "?" + ps;
	         }
	         httpGet = new HttpGet(url);
	         httpGet.setConfig(requestConfig);
	         CloseableHttpResponse response = httpClient.execute(httpGet);
	         HttpEntity httpEntity = response.getEntity();
	         System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
	     } catch (ClientProtocolException e) {
	         e.printStackTrace();
	     } catch (IOException e) {
	         e.printStackTrace();
	     }finally{
	         try {
	             if(httpGet!=null){
	                 httpGet.releaseConnection();
	             }
	             if(httpClient!=null){
	                 httpClient.close();
	             }
	         } catch (IOException e) {
	             e.printStackTrace();
	         }
	     }
	 }
	
	/**
     * 向指定 URL 发送Post方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param 参数放到Map中
     * @return 所代表远程资源的响应结果
     */
	public static void post(String url, Map<String, String> params){
	     CloseableHttpClient httpClient = null;
	     HttpPost httpPost = null;
	     try {
	         httpClient = HttpClients.createDefault();
	         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
	         httpPost = new HttpPost(url);
	         httpPost.setConfig(requestConfig);
	         List<NameValuePair> ps = new ArrayList<NameValuePair>();
	         for (String pKey : params.keySet()) {
	             ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
	         }
	         httpPost.setEntity(new UrlEncodedFormEntity(ps));
	         CloseableHttpResponse response = httpClient.execute(httpPost);
	         HttpEntity httpEntity = response.getEntity();
	         System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
	     } catch (ClientProtocolException e) {
	         e.printStackTrace();
	     } catch (IOException e) {
	         e.printStackTrace();
	     }finally{
	         try {
	             if(httpPost!=null){
	                 httpPost.releaseConnection();
	             }
	             if(httpClient!=null){
	                 httpClient.close();
	             }
	         } catch (IOException e) {
	             e.printStackTrace();
	         }
	     }
	 }
	
	/**
     * 向指定 URL 发送Post方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param RAW 参数传递:
     * @return 所代表远程资源的响应结果
     */
	public static void postRaw(String url, String body){
	    CloseableHttpClient httpClient = null;
	    HttpPost httpPost = null;
	    try {
	        httpClient = HttpClients.createDefault();
	        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
	        httpPost = new HttpPost(url);
	        httpPost.setConfig(requestConfig);
	        httpPost.setEntity(new StringEntity(body));
	        CloseableHttpResponse response = httpClient.execute(httpPost);
	        HttpEntity httpEntity = response.getEntity();
	        //System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
	        
	        InputStream in1 = httpEntity.getContent();
	        StringBuffer sb=new StringBuffer();
			try {
			      String readLine=new String();
			      BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));
			      while((readLine=responseReader.readLine())!=null){
			        sb.append(readLine).append("\n");
			      }
			      responseReader.close();
			      System.out.println("----------sb="+sb.toString());
				
			} catch (Exception e1) {
				e1.printStackTrace();
			}
	        
	       
	        
	    } catch (ClientProtocolException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }finally{
	        try {
	            if(httpPost!=null){
	                httpPost.releaseConnection();
	            }
	            if(httpClient!=null){
	                httpClient.close();
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	}
	
	/**
     * 向指定 URL 发送Post方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param RAW 参数传递:
     * @return 所代表远程资源的响应结果
     */
	public static String sedPostAsRaw(JSONObject jsonParam,String urls) {
		StringBuffer sb=new StringBuffer();
		try {
			// 创建url资源
			URL url = new URL(urls);
			// 建立http连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置允许输出
			conn.setDoOutput(true);
            // 设置允许输入
            conn.setDoInput(true);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setRequestMethod("POST");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            // 转换为字节数组
            byte[] data = (jsonParam.toString()).getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 设置文件类型:
            conn.setRequestProperty("contentType", "application/json");
            // 开始连接请求
            conn.connect();		
            OutputStream out = new DataOutputStream(conn.getOutputStream()) ;
			// 写入请求的字符串
			out.write((jsonParam.toString()).getBytes());
			out.flush();
			out.close();
 
			//System.out.println(conn.getResponseCode());
			
			// 请求返回的状态
			if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
				//System.out.println("连接成功");
				// 请求返回的数据
				InputStream in1 = conn.getInputStream();
				try {
				      String readLine=new String();
				      BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));
				      while((readLine=responseReader.readLine())!=null){
				        sb.append(readLine).append("\n");
				      }
				      responseReader.close();
				      //System.out.println(sb.toString());
					
				} catch (Exception e1) {
					e1.printStackTrace();
					return sb.toString();
				}
			}else{
				return sb.append(conn.getResponseCode()).toString();
			}
		} catch (Exception e) {
			return sb.toString();
		}
		
		return sb.toString();
 
	}



	public static void main(String[] args) {
		JSONObject jsonParam = new JSONObject();
		jsonParam.put("method", "tools_borrow");
		String url="http://148.70.14.242:8000/webrequest";
		//postRaw(url,jsonParam.toString());
		String data = sedPostAsRaw(jsonParam,url);
		System.out.println(data);
		if("400".equals(data)){
			System.out.println("网络连接异常");
		}else{
			System.out.println(data);
	        //返回的是一个[{}]格式的字符串时:                               
	        JSONObject jsonObject = new JSONObject(data);  
	        String response_code = jsonObject.getString("response_code");
	        if("0".equals(response_code)){//表示成功
	        	String prisoner = jsonObject.getString("prisoner");
		        JSONArray toolsArray = jsonObject.getJSONArray("tools");
		        System.out.println(prisoner);
		        //有质量问题的产品,必须要重新分包
 				if(toolsArray != null && toolsArray.length() > 0){
 					//循环有问题的产品包数
 					for (int j = 0; j < toolsArray.length(); j++) {
							JSONObject toolinfo = toolsArray.getJSONObject(j);
							String tools_name = Tools.getStr(toolinfo.getString("tools_name"));
 					}
 				}
	        }
		}
	}
}
